import os
import requests
import json
import logging
import time
import threading
import zipfile
from pathlib import Path
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from dotenv import load_dotenv

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    filename='offline_content_debug.log',
    filemode='a'
)
logger = logging.getLogger('offline_content')

# 调试模式标志
DEBUG_MODE = False  # 改为False以使用实际的LLM API调用

# 加载环境变量
load_dotenv()

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 获取API密钥
# OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
OPENAI_API_KEY = "jina_b8e7dd0e5f7a45ecb03429f5dcc5de92ZREJN73p43A6UNZ5jsnjm7PnCT7A"
if not OPENAI_API_KEY:
    raise ValueError("请在.env文件中设置OPENAI_API_KEY")

# API端点
# OPENAI_API_URL = "https://api.openai.com/v1/chat/completions"
OPENAI_API_URL = "https://deepsearch.jina.ai/v1/chat/completions"

# 可用目的地API
@app.route('/api/available_destinations', methods=['GET'])
def available_destinations():
    logger.debug("请求可用目的地API")
    # 当前开放的目的地
    available = {
        'tokyo': {
            'name': '东京',
            'country': '日本',
            'language': 'ja',
            'available': True,
            'packages': ['language', 'map', 'culture'],
            'languageSize': 45,
            'mapSize': 85,
            'cultureSize': 30
        },
        'paris': {
            'name': '巴黎',
            'country': '法国',
            'language': 'fr',
            'available': True,
            'packages': ['language', 'map', 'culture'],
            'languageSize': 50,
            'mapSize': 90,
            'cultureSize': 35
        },
        'newyork': {
            'name': '纽约',
            'country': '美国',
            'language': 'en',
            'available': True,
            'packages': ['language', 'map', 'culture'],
            'languageSize': 40,
            'mapSize': 95,
            'cultureSize': 32
        },
        'rome': {
            'name': '罗马',
            'country': '意大利',
            'language': 'it',
            'available': False,
            'coming_soon': True,
            'eta': '2025年7月'
        },
        'bangkok': {
            'name': '曼谷',
            'country': '泰国',
            'language': 'th',
            'available': False,
            'coming_soon': True,
            'eta': '2025年8月'
        },
        'london': {
            'name': '伦敦',
            'country': '英国',
            'language': 'en',
            'available': False,
            'coming_soon': True,
            'eta': '2025年9月'
        }
    }
    
    return jsonify({
        'destinations': available,
        'total_available': 3,
        'coming_soon': 3
    })

# 离线内容包下载API
@app.route('/api/download_package', methods=['POST'])
def download_package():
    logger.debug(f"收到下载请求: {request.json}")
    data = request.json
    destination = data.get('destination', '')
    package_type = data.get('package_type', '')
    
    # 检查目的地是否可用
    destinations = {
        'tokyo': {
            'name': '东京',
            'country': '日本',
            'language': 'ja',
            'available': True
        },
        'paris': {
            'name': '巴黎',
            'country': '法国',
            'language': 'fr',
            'available': True
        },
        'newyork': {
            'name': '纽约',
            'country': '美国',
            'language': 'en',
            'available': True
        },
        'rome': {
            'name': '罗马',
            'country': '意大利',
            'language': 'it',
            'available': False,
            'eta': '2025年7月'
        },
        'bangkok': {
            'name': '曼谷',
            'country': '泰国',
            'language': 'th',
            'available': False,
            'eta': '2025年8月'
        },
        'london': {
            'name': '伦敦',
            'country': '英国',
            'language': 'en',
            'available': False,
            'eta': '2025年9月'
        }
    }
    
    if not destination or not package_type:
        logger.warning(f"请求缺少必要参数: destination={destination}, package_type={package_type}")
        return jsonify({"error": "请提供目的地和包类型"}), 400
    
    if destination not in destinations:
        logger.warning(f"不支持的目的地: {destination}")
        return jsonify({"error": "不支持的目的地"}), 400
    
    if not destinations[destination]['available']:
        logger.info(f"请求了未开放的目的地: {destination}")
        return jsonify({
            "error": "目的地暂不可用",
            "destination": destination,
            "name": destinations[destination]['name'],
            "eta": destinations[destination]['eta']
        }), 400
    
    if package_type not in ['language', 'map', 'culture']:
        logger.warning(f"不支持的包类型: {package_type}")
        return jsonify({"error": "不支持的包类型"}), 400
    
    # 生成唯一下载ID
    download_id = f"{destination}_{package_type}_{int(time.time())}"
    logger.info(f"生成下载ID: {download_id}")
    
    # 包大小信息
    package_sizes = {
        'tokyo': {'language': 45, 'map': 85, 'culture': 30},
        'paris': {'language': 50, 'map': 90, 'culture': 35},
        'newyork': {'language': 40, 'map': 95, 'culture': 32}
    }
    
    # 创建离线内容目录
    offline_dir = Path("offline_content")
    offline_dir.mkdir(exist_ok=True)
    logger.debug(f"创建离线内容目录: {offline_dir}")
    
    # 在后台线程中生成内容
    threading.Thread(
        target=generate_offline_content,
        args=(download_id, destination, package_type, destinations[destination])
    ).start()
    
    # 返回下载信息
    return jsonify({
        "success": True,
        "destination": destination,
        "package_type": package_type,
        "size_mb": package_sizes[destination][package_type],
        "download_id": download_id,
        "status_url": f"/api/download_status/{download_id}"
    })

# 下载状态API
@app.route('/api/download_status/<download_id>', methods=['GET'])
def download_status(download_id):
    logger.debug(f"检查下载状态: {download_id}")
    # 解析下载ID
    try:
        parts = download_id.split('_')
        destination = parts[0]
        package_type = parts[1]
    except:
        logger.error(f"无效的下载ID: {download_id}")
        return jsonify({"error": "无效的下载ID"}), 400
    
    # 检查文件是否已生成
    offline_dir = Path("offline_content")
    zip_file = offline_dir / f"{download_id}.zip"
    
    if zip_file.exists():
        logger.info(f"下载已完成: {download_id}")
        return jsonify({
            "status": "completed",
            "download_url": f"/api/download_file/{download_id}",
            "destination": destination,
            "package_type": package_type
        })
    else:
        # 检查是否正在生成
        temp_file = offline_dir / f"{download_id}.generating"
        if temp_file.exists():
            # 读取进度
            try:
                with open(temp_file, 'r') as f:
                    progress = f.read().strip()
                    progress = int(progress) if progress.isdigit() else 0
                logger.debug(f"下载进度: {download_id} - {progress}%")
            except Exception as e:
                logger.error(f"读取进度失败: {e}")
                progress = 0
                
            return jsonify({
                "status": "generating",
                "progress": progress,
                "destination": destination,
                "package_type": package_type
            })
        else:
            logger.warning(f"下载任务不存在: {download_id}")
            return jsonify({
                "status": "not_found",
                "error": "下载任务不存在或已过期"
            }), 404

# 文件下载API
@app.route('/api/download_file/<download_id>', methods=['GET'])
def download_file(download_id):
    logger.info(f"请求下载文件: {download_id}")
    
    offline_dir = Path("offline_content")
    zip_file = offline_dir / f"{download_id}.zip"
    
    if zip_file.exists():
        logger.debug(f"发送文件: {zip_file}")
        return send_file(
            zip_file,
            mimetype='application/zip',
            as_attachment=True,
            download_name=f"{download_id}.zip"
        )
    else:
        logger.error(f"文件不存在: {download_id}")
        return jsonify({"error": "文件不存在"}), 404

# 使用LLM生成内容
def generate_content_with_llm(prompt, system_prompt):
    if DEBUG_MODE:
        logger.debug(f"模拟生成内容，提示: {prompt[:100]}...")
        # 返回模拟数据
        if "短语" in prompt:
            return json.dumps([
                {"phrase": "こんにちは", "pronunciation": "Kon'nichiwa", "translation": "你好", "usage": "打招呼"},
                {"phrase": "ありがとう", "pronunciation": "Arigatō", "translation": "谢谢", "usage": "表达感谢"}
            ], ensure_ascii=False)
        elif "对话" in prompt:
            return json.dumps({"scenario": "餐厅", "conversation": [{"speaker": "顾客", "text": "一个示例对话"}]})
        elif "POI" in prompt:
            return json.dumps([
                {"id": "poi1", "name": "东京塔", "type": "景点", "coordinates": [139.7454, 35.6586], "address": "东京都港区芝公园4丁目2-8", "description": "东京的标志性建筑"}
            ])
        elif "路线" in prompt:
            return json.dumps([
                {"name": "东京一日游", "description": "东京经典景点一日游", "duration": "8小时", "points": [{"poi_id": "poi1", "name": "东京塔", "stay_time": "1小时"}]}
            ])
        else:
            return json.dumps({"title": "示例内容", "content": "这是调试模式下的示例内容"})
    else:
        headers = {
            "Authorization": f"Bearer {OPENAI_API_KEY}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "model": "gpt-3.5-turbo",
            "messages": [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": prompt}
            ],
            "temperature": 0.7
        }
        
        try:
            logger.debug(f"调用LLM API生成内容")
            response = requests.post(OPENAI_API_URL, headers=headers, json=payload)
            response.raise_for_status()
            result = response.json()
            content = result["choices"][0]["message"]["content"]
            return content
        except Exception as e:
            logger.error(f"生成内容失败: {str(e)}")
            # 返回一个简单的错误JSON
            return json.dumps({"error": str(e)})

# 生成离线内容
def generate_offline_content(download_id, destination, package_type, destination_info):
    logger.info(f"开始生成离线内容: {download_id}")
    offline_dir = Path("offline_content")
    temp_file = offline_dir / f"{download_id}.generating"
    zip_file = offline_dir / f"{download_id}.zip"
    content_dir = offline_dir / download_id
    
    try:
        # 创建临时文件记录进度
        with open(temp_file, 'w') as f:
            f.write("0")
        
        # 创# 创建内容目录
        content_dir.mkdir(exist_ok=True)
        logger.debug(f"创建内容目录: {content_dir}")
        
        # 根据包类型生成不同内容
        if package_type == 'language':
            if DEBUG_MODE:
                generate_language_package_debug(content_dir, destination, destination_info, temp_file)
            else:
                generate_language_package(content_dir, destination, destination_info, temp_file)
        elif package_type == 'culture':
            if DEBUG_MODE:
                generate_culture_package_debug(content_dir, destination, destination_info, temp_file)
            else:
                generate_culture_package(content_dir, destination, destination_info, temp_file)
        elif package_type == 'map':
            if DEBUG_MODE:
                generate_map_package_debug(content_dir, destination, destination_info, temp_file)
            else:
                generate_map_package(content_dir, destination, destination_info, temp_file)
        
        # 创建ZIP文件
        logger.info(f"创建ZIP文件: {zip_file}")
        with zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
            for file in content_dir.glob('**/*'):
                if file.is_file():
                    zipf.write(file, file.relative_to(content_dir))
        
        # 更新进度为100%
        with open(temp_file, 'w') as f:
            f.write("100")
        logger.info(f"内容生成完成: {download_id}")
            
    except Exception as e:
        # 记录错误
        logger.error(f"生成内容失败: {download_id} - {str(e)}")
        with open(offline_dir / f"{download_id}_error.log", 'w') as f:
            f.write(str(e))
    finally:
        # 清理临时文件和目录
        import shutil
        if content_dir.exists():
            shutil.rmtree(content_dir)
            logger.debug(f"清理内容目录: {content_dir}")

# 实际的语言包生成函数
def generate_language_package(content_dir, destination, destination_info, progress_file):
    logger.info(f"生成语言包: {destination}")
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("10")
    
    # 生成短语列表
    system_prompt = "你是一个旅游语言专家，请为旅行者提供目的地常用短语。"
    prompt = f"请为前往{destination_info['name']}({destination_info['country']})的旅行者提供20个最常用的当地语言短语，包括发音、中文翻译和使用场景。以JSON格式返回，格式为[{{\"phrase\": \"短语\", \"pronunciation\": \"发音\", \"translation\": \"翻译\", \"usage\": \"使用场景\"}}]"
    
    phrases_json = generate_content_with_llm(prompt, system_prompt)
    with open(content_dir / "phrases.json", 'w', encoding='utf-8') as f:
        f.write(phrases_json)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("40")
    
    # 生成对话示例
    system_prompt = "你是一个旅游语言专家，请为旅行者提供实用的对话示例。"
    prompt = f"请为前往{destination_info['name']}({destination_info['country']})的旅行者提供5个常见场景的对话示例，使用当地语言和中文。以JSON格式返回，格式为{{\"scenario\": \"场景\", \"conversation\": [{{\"speaker\": \"角色\", \"text\": \"对话内容\", \"translation\": \"中文翻译\"}}]}}"
    
    conversations_json = generate_content_with_llm(prompt, system_prompt)
    with open(content_dir / "conversations.json", 'w', encoding='utf-8') as f:
        f.write(conversations_json)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("70")
    
    # 创建信息文件
    info = {
        "destination": destination,
        "name": destination_info['name'],
        "country": destination_info['country'],
        "language": destination_info.get('language', 'en'),
        "package_type": "language",
        "version": "1.0",
        "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
        "content": ["phrases.json", "conversations.json"]
    }
    
    with open(content_dir / "info.json", 'w', encoding='utf-8') as f:
        json.dump(info, f, ensure_ascii=False, indent=2)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("90")
    
    logger.info(f"语言包生成完成: {destination}")

# 简化的调试版语言包生成函数
def generate_language_package_debug(content_dir, destination, destination_info, progress_file):
    logger.debug(f"使用调试模式生成语言包: {destination}")
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("10")
    
    time.sleep(2)  # 模拟处理时间
    
    # 创建简单的JSON文件
    simple_phrases = [
        {"phrase": "Hello", "pronunciation": "həˈloʊ", "translation": "你好", "usage": "打招呼"},
        {"phrase": "Thank you", "pronunciation": "θæŋk juː", "translation": "谢谢", "usage": "表达感谢"},
        {"phrase": "Excuse me", "pronunciation": "ɪkˈskjuːz miː", "translation": "打扰一下", "usage": "引起注意"}
    ]
    
    with open(content_dir / "phrases.json", 'w', encoding='utf-8') as f:
        json.dump(simple_phrases, f, ensure_ascii=False, indent=2)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("50")
    
    time.sleep(2)  # 模拟处理时间
    
    # 创建信息文件
    info = {
        "destination": destination,
        "name": destination_info['name'],
        "country": destination_info['country'],
        "language": destination_info.get('language', 'en'),
        "package_type": "language",
        "version": "1.0",
        "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
        "content": ["phrases.json"]
    }
    
    with open(content_dir / "info.json", 'w', encoding='utf-8') as f:
        json.dump(info, f, ensure_ascii=False, indent=2)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("90")
    
    logger.debug(f"语言包生成完成: {destination}")

# 实际的文化包生成函数
def generate_culture_package(content_dir, destination, destination_info, progress_file):
    logger.info(f"生成文化包: {destination}")
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("10")
    
    # 生成历史文化内容
    system_prompt = "你是一个旅游文化专家，请为旅行者提供目的地的历史文化信息。"
    prompt = f"请为前往{destination_info['name']}({destination_info['country']})的旅行者提供该地区的历史文化概述，包括重要历史事件、文化特色等。以JSON格式返回，格式为{{\"title\": \"标题\", \"overview\": \"概述\", \"sections\": [{{\"subtitle\": \"子标题\", \"content\": \"内容\"}}]}}"
    
    history_json = generate_content_with_llm(prompt, system_prompt)
    with open(content_dir / "history.json", 'w', encoding='utf-8') as f:
        f.write(history_json)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("40")
    
    # 生成风俗习惯内容
    system_prompt = "你是一个旅游文化专家，请为旅行者提供目的地的风俗习惯信息。"
    prompt = f"请为前往{destination_info['name']}({destination_info['country']})的旅行者提供该地区的风俗习惯、禁忌和礼仪指南。以JSON格式返回，格式为{{\"customs\": [{{\"title\": \"标题\", \"description\": \"描述\"}}], \"taboos\": [{{\"title\": \"禁忌\", \"description\": \"描述\"}}], \"etiquette\": [{{\"situation\": \"场景\", \"advice\": \"建议\"}}]}}"
    
    customs_json = generate_content_with_llm(prompt, system_prompt)
    with open(content_dir / "customs.json", 'w', encoding='utf-8') as f:
        f.write(customs_json)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("70")
    
    # 创建信息文件
    info = {
        "destination": destination,
        "name": destination_info['name'],
        "country": destination_info['country'],
        "package_type": "culture",
        "version": "1.0",
        "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
        "content": ["history.json", "customs.json"]
    }
    
    with open(content_dir / "info.json", 'w', encoding='utf-8') as f:
        json.dump(info, f, ensure_ascii=False, indent=2)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("90")
    
    logger.info(f"文化包生成完成: {destination}")

# 简化的调试版文化包生成函数
def generate_culture_package_debug(content_dir, destination, destination_info, progress_file):
    logger.debug(f"使用调试模式生成文化包: {destination}")
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("10")
    
    time.sleep(2)  # 模拟处理时间
    
    # 创建简单的JSON文件
    history = {
        "title": f"{destination_info['name']}历史",
        "overview": f"这是{destination_info['name']}的历史概述。",
        "sections": [
            {
                "subtitle": "早期历史",
                "content": "这是早期历史内容。"
            },
            {
                "subtitle": "现代发展",
                "content": "这是现代发展内容。"
            }
        ]
    }
    
    with open(content_dir / "history.json", 'w', encoding='utf-8') as f:
        json.dump(history, f, ensure_ascii=False, indent=2)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("50")
    
    time.sleep(2)  # 模拟处理时间
    
    # 创建信息文件
    info = {
        "destination": destination,
        "name": destination_info['name'],
        "country": destination_info['country'],
        "package_type": "culture",
        "version": "1.0",
        "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
        "content": ["history.json"]
    }
    
    with open(content_dir / "info.json", 'w', encoding='utf-8') as f:
        json.dump(info, f, ensure_ascii=False, indent=2)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("90")
    
    logger.debug(f"文化包生成完成: {destination}")

# 实际的地图包生成函数
def generate_map_package(content_dir, destination, destination_info, progress_file):
    logger.info(f"生成地图包: {destination}")
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("10")
    
    # 生成POI点位信息
    system_prompt = "你是一个旅游地图专家，请为旅行者提供目的地的兴趣点信息。"
    prompt = f"请为前往{destination_info['name']}({destination_info['country']})的旅行者提供15个重要的兴趣点(POI)，包括景点、餐厅、购物中心等。以JSON格式返回，格式为[{{\"id\": \"唯一ID\", \"name\": \"名称\", \"type\": \"类型\", \"coordinates\": [经度, 纬度], \"address\": \"地址\", \"description\": \"描述\"}}]"
    
    pois_json = generate_content_with_llm(prompt, system_prompt)
    with open(content_dir / "pois.json", 'w', encoding='utf-8') as f:
        f.write(pois_json)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("40")
    
    # 生成推荐路线
    system_prompt = "你是一个旅游路线规划专家，请为旅行者提供目的地的推荐路线。"
    prompt = f"请为前往{destination_info['name']}({destination_info['country']})的旅行者提供3条推荐旅游路线。以JSON格式返回，格式为[{{\"name\": \"路线名称\", \"description\": \"路线描述\", \"duration\": \"持续时间\", \"points\": [{{\"poi_id\": \"POI的ID\", \"name\": \"地点名称\", \"stay_time\": \"停留时间\"}}]}}]"
    
    routes_json = generate_content_with_llm(prompt, system_prompt)
    with open(content_dir / "routes.json", 'w', encoding='utf-8') as f:
        f.write(routes_json)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("70")
    
    # 创建信息文件
    info = {
        "destination": destination,
        "name": destination_info['name'],
        "country": destination_info['country'],
        "package_type": "map",
        "version": "1.0",
        "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
        "content": ["pois.json", "routes.json"]
    }
    
    with open(content_dir / "info.json", 'w', encoding='utf-8') as f:
        json.dump(info, f, ensure_ascii=False, indent=2)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("90")
    
    logger.info(f"地图包生成完成: {destination}")

# 简化的调试版地图包生成函数
def generate_map_package_debug(content_dir, destination, destination_info, progress_file):
    logger.debug(f"使用调试模式生成地图包: {destination}")
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("10")
    
    time.sleep(2)  # 模拟处理时间
    
    # 创建简单的JSON文件
    pois = [
        {
            "id": "poi1",
            "name": f"{destination_info['name']}塔",
            "type": "景点",
            "coordinates": [0, 0],
            "address": f"{destination_info['name']}中心",
            "description": f"{destination_info['name']}的标志性建筑"
        },
        {
            "id": "poi2",
            "name": f"{destination_info['name']}博物馆",
            "type": "博物馆",
            "coordinates": [0.01, 0.01],
            "address": f"{destination_info['name']}文化区",
            "description": f"展示{destination_info['name']}历史的博物馆"
        }
    ]
    
    with open(content_dir / "pois.json", 'w', encoding='utf-8') as f:
        json.dump(pois, f, ensure_ascii=False, indent=2)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("50")
    
    time.sleep(2)  # 模拟处理时间
    
    # 创建信息文件
    info = {
        "destination": destination,
        "name": destination_info['name'],
        "country": destination_info['country'],
        "package_type": "map",
        "version": "1.0",
        "created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
        "content": ["pois.json"]
    }
    
    with open(content_dir / "info.json", 'w', encoding='utf-8') as f:
        json.dump(info, f, ensure_ascii=False, indent=2)
    
    # 更新进度
    with open(progress_file, 'w') as f:
        f.write("90")
    
    logger.debug(f"地图包生成完成: {destination}")

# 调试API - 查看所有下载任务
@app.route('/api/debug/downloads', methods=['GET'])
def debug_downloads():
    if not DEBUG_MODE:
        return jsonify({"error": "Debug mode is disabled"}), 403
        
    logger.debug("请求调试API: 查看所有下载任务")
    offline_dir = Path("offline_content")
    
    # 收集所有下载任务
    downloads = []
    
    # 检查生成中的任务
    for file in offline_dir.glob("*.generating"):
        try:
            with open(file, 'r') as f:
                progress = f.read().strip()
            
            download_id = file.stem
            parts = download_id.split('_')
            
            downloads.append({
                "id": download_id,
                "destination": parts[0] if len(parts) > 0 else "unknown",
                "package_type": parts[1] if len(parts) > 1 else "unknown",
                "status": "generating",
                "progress": progress
            })
        except Exception as e:
            logger.error(f"读取生成进度失败: {e}")
    
    # 检查已完成的任务
    for file in offline_dir.glob("*.zip"):
        download_id = file.stem
        parts = download_id.split('_')
        
        downloads.append({
            "id": download_id,
            "destination": parts[0] if len(parts) > 0 else "unknown",
            "package_type": parts[1] if len(parts) > 1 else "unknown",
            "status": "completed",
            "size": file.stat().st_size
        })
    
    return jsonify({
        "downloads": downloads,
        "count": len(downloads)
    })

# 调试API - 测试错误情况
@app.route('/api/debug/test_error', methods=['POST'])
def test_error():
    if not DEBUG_MODE:
        return jsonify({"error": "Debug mode is disabled"}), 403
        
    logger.debug(f"请求调试API: 测试错误情况 - {request.json}")
    error_type = request.json.get('error_type', '')
    
    if error_type == 'api_error':
        logger.debug("模拟API错误")
        return jsonify({"error": "模拟API错误"}), 500
    elif error_type == 'timeout':
        logger.debug("模拟超时")
        time.sleep(30)  # 模拟超时
        return jsonify({"result": "timeout test completed"})
    elif error_type == 'corrupt_zip':
        # 创建一个损坏的ZIP文件用于测试
        logger.debug("创建损坏的ZIP文件")
        offline_dir = Path("offline_content")
        with open(offline_dir / "corrupt_test.zip", 'wb') as f:
            f.write(b'This is not a valid ZIP file')
        return jsonify({"corrupt_file": "corrupt_test.zip"})
    
    return jsonify({"message": "Unknown error type"})

# 管理存储空间API
@app.route('/api/storage/info', methods=['GET'])
def storage_info():
    offline_dir = Path("offline_content")
    
    # 计算已使用空间
    used_space = 0
    downloaded_packages = []
    
    if offline_dir.exists():
        # 统计ZIP文件大小
        for zip_file in offline_dir.glob("*.zip"):
            file_size = zip_file.stat().st_size
            used_space += file_size
            
            # 解析包信息
            download_id = zip_file.stem
            parts = download_id.split('_')
            if len(parts) >= 2:
                destination = parts[0]
                package_type = parts[1]
                
                # 获取目的地信息
                destinations = {
                    'tokyo': {'name': '东京', 'country': '日本', 'language': 'ja'},
                    'paris': {'name': '巴黎', 'country': '法国', 'language': 'fr'},
                    'newyork': {'name': '纽约', 'country': '美国', 'language': 'en'}
                }
                
                dest_info = destinations.get(destination, {'name': destination, 'country': '未知'})
                
                downloaded_packages.append({
                    "id": download_id,
                    "destination": destination,
                    "name": dest_info['name'],
                    "package_type": package_type,
                    "size": file_size,
                    "download_date": time.strftime("%Y-%m-%d", time.localtime(zip_file.stat().st_mtime))
                })
    
    # 转换为MB
    used_space_mb = round(used_space / (1024 * 1024), 2)
    
    return jsonify({
        "used_space": used_space,
        "used_space_mb": used_space_mb,
        "packages": downloaded_packages,
        "package_count": len(downloaded_packages)
    })

# 删除离线内容包API
@app.route('/api/storage/delete/<download_id>', methods=['DELETE'])
def delete_package(download_id):
    offline_dir = Path("offline_content")
    zip_file = offline_dir / f"{download_id}.zip"
    
    if zip_file.exists():
        try:
            zip_file.unlink()
            logger.info(f"删除离线内容包: {download_id}")
            return jsonify({"success": True, "message": f"已删除内容包: {download_id}"})
        except Exception as e:
            logger.error(f"删除内容包失败: {download_id} - {str(e)}")
            return jsonify({"error": f"删除失败: {str(e)}"}), 500
    else:
        return jsonify({"error": "内容包不存在"}), 404

# 获取文化知识库API
@app.route('/api/culture/<destination>', methods=['GET'])
def get_culture_info(destination):
    offline_dir = Path("offline_content")
    
    # 查找该目的地的文化包
    culture_packages = list(offline_dir.glob(f"{destination}_culture_*.zip"))
    
    if not culture_packages:
        return jsonify({
            "error": "离线文化数据不可用",
            "message": "请先下载文化知识库"
        }), 404
    
    # 使用最新的文化包
    latest_package = sorted(culture_packages, key=lambda x: x.stat().st_mtime, reverse=True)[0]
    
    try:
        # 解压并读取文化数据
        with zipfile.ZipFile(latest_package, 'r') as zip_ref:
            with zip_ref.open('info.json') as f:
                info = json.load(f)
            
            with zip_ref.open('history.json') as f:
                history = json.load(f)
            
            # 如果存在风俗习惯文件
            customs = None
            if 'customs.json' in [file.filename for file in zip_ref.filelist]:
                with zip_ref.open('customs.json') as f:
                    customs = json.load(f)
        
        return jsonify({
            "destination": destination,
            "name": info["name"],
            "country": info["country"],
            "history": history,
            "customs": customs,
            "version": info.get("version", "1.0"),
            "updated_at": info.get("created_at", "未知")
        })
    except Exception as e:
        logger.error(f"读取文化数据失败: {destination} - {str(e)}")
        return jsonify({
            "error": "读取文化数据失败",
            "message": str(e)
        }), 500

# 文本翻译API
@app.route('/api/translate', methods=['POST'])
def translate_text():
    data = request.json
    text = data.get('text', '')
    source_lang = data.get('source_lang', 'auto')
    target_lang = data.get('target_lang', 'zh')
    
    if not text:
        return jsonify({"error": "请提供需要翻译的文本"}), 400
    
    # 调用LLM进行翻译
    system_prompt = "你是一个专业的翻译助手，请准确翻译用户提供的文本。"
    
    if source_lang == 'auto':
        prompt = f"请将以下文本翻译成{target_lang}语言，保持原文的意思和语气：\n\n{text}"
    else:
        prompt = f"请将以下{source_lang}文本翻译成{target_lang}语言，保持原文的意思和语气：\n\n{text}"
    
    try:
        translation = generate_content_with_llm(prompt, system_prompt)
        
        # 尝试解析JSON，如果不是JSON格式，则直接使用文本
        try:
            result = json.loads(translation)
            if isinstance(result, dict) and "translation" in result:
                translation = result["translation"]
        except:
            # 不是JSON格式，直接使用文本
            pass
        
        return jsonify({
            "original": text,
            "translation": translation,
            "source_lang": source_lang,
            "target_lang": target_lang
        })
    except Exception as e:
        logger.error(f"翻译失败: {str(e)}")
        return jsonify({"error": f"翻译失败: {str(e)}"}), 500

# 情境化翻译建议API
@app.route('/api/translate/contextual', methods=['POST'])
def contextual_translation():
    data = request.json
    text = data.get('text', '')
    context = data.get('context', '')
    source_lang = data.get('source_lang', 'auto')
    target_lang = data.get('target_lang', 'zh')
    
    if not text:
        return jsonify({"error": "请提供需要翻译的文本"}), 400
    
    # 调用LLM提供情境化翻译
    system_prompt = "你是一个专业的翻译助手，请根据用户提供的情境，给出最适合该情境的翻译。"
    
    prompt = f"""请根据以下情境，提供最适合的翻译：

原文: {text}
情境: {context}
源语言: {source_lang}
目标语言: {target_lang}

请提供以下内容:
1. 直译
2. 情境化翻译（考虑文化背景和使用场景）
3. 替代表达（如有更地道的表达方式）
4. 文化注释（如有必要）

以JSON格式返回，格式为:
{{
  "literal": "直译",
  "contextual": "情境化翻译",
  "alternatives": ["替代表达1", "替代表达2"],
  "cultural_notes": "文化注释"
}}
"""
    
    try:
        result = generate_content_with_llm(prompt, system_prompt)
        
        # 尝试解析JSON
        try:
            translation = json.loads(result)
        except:
            # 如果不是JSON格式，返回原始结果
            translation = {"result": result}
        
        return jsonify({
            "original": text,
            "context": context,
            "translations": translation,
            "source_lang": source_lang,
            "target_lang": target_lang
        })
    except Exception as e:
        logger.error(f"情境化翻译失败: {str(e)}")
        return jsonify({"error": f"情境化翻译失败: {str(e)}"}), 500

if __name__ == '__main__':
    app.run(debug=False, port=5001)  # 使用不同的端口避免与主API冲突